package com.xzx.mybatis;

import com.xzx.mybatis.mapper.Blog2Mapper;
import com.xzx.mybatis.mapper.BlogMapper;
import com.xzx.mybatis.po.Blog;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/6/15 18:11
 */
public class SqlSessionTest {
    public static void main(String[] args) throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//        testXml(sqlSessionFactory);
//        testInterfaceXml(sqlSessionFactory);
        testInterface(sqlSessionFactory);
    }

    private static void testInterface(SqlSessionFactory sqlSessionFactory) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            Blog2Mapper mapper = sqlSession.getMapper(Blog2Mapper.class);
            Blog blog = mapper.selectBlog(1);
            System.out.println(blog);
        }
    }

    private static void testInterfaceXml(SqlSessionFactory sqlSessionFactory) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
            Blog blog = blogMapper.selectBlog(1);
            System.out.println(blog);
        }
    }

    private static void testXml(SqlSessionFactory sqlSessionFactory) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            // com.xzx.BlogMapper 这个是namespace
            Blog blog = sqlSession.selectOne("com.xzx.BlogMapper.selectBlog", 1);
            System.out.println(blog);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
}
